import 'dart:io';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_member/routes/application.dart';
import 'package:flutter_member/utils/Counter.dart';
import 'package:flutter_member/widget/GridViewItem.dart';
import 'package:flutter_member/widget/coin_ranking_listItem_skeleton.dart';
import 'package:flutter_member/widget/course_tutorial.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:provide/provide.dart';
import 'package:shimmer/shimmer.dart';

/// 首页的主入口
class IndexPage extends StatefulWidget {
  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>  with SingleTickerProviderStateMixin{
  ParseUser user;

  //課程滑動控制器
  var _controller = ScrollController();
  var controllerIndex;

  //補習滑動控制器
  var _ieItsController = ScrollController();
  var _ieItsControllerIndex;
  var widgetWidth = 160;

  bool isNews = true;

  /*-----------課程Start--------------*/

  List<dynamic> listCourse = [];

  /// 課程獲取狀態
  bool _loadingCou = true;

  /*-----------課程END-------------*/

  ScrollController _scrollController = ScrollController();
  int _titleAlpha = 0; //范围 0-255
  int titleHeight = 50;

  /*--------補習Start---------*/
  List<dynamic> _dyServiceList = [];

  /// 補習數據請求狀態
  bool _loadingTui = true;

  /*--------補習END--------*/

  bool isPerformingRequest = false;
  List<double> list;

  //課程
  Future<void> _getCourse() async {
    listCourse.clear();
    var queryCourse = QueryBuilder(ParseObject('CourseClass'))
      ..includeObject(['course']);
    var rep = await queryCourse.query();
    if (rep.statusCode == 200 && rep.results != null) {
      setState(() {
        _loadingCou = false;
        rep.results.map((e) {
          return listCourse.add({
            'objectId': e['objectId'],
            'title': e['title'],
            'src': e['course']['cover']['url'],
            'courseCategory': e['course']['title'],
            'blView': false,
            'titleColor': Colors.amberAccent
          });
        }).toList();
      });
    } else {
      setState(() => _loadingCou = false);
    }
    ;
  }

  List<dynamic> listStu = [];

  /// 获得学生状态
  Future<void> getMemberStudent() async {
    listStu.clear();
    final ParseUser user = await ParseUser.currentUser();
    print(user.objectId);
    if (user != null && user.get("member") != null) {
      var query = QueryBuilder(ParseObject("Member"))
        ..whereEqualTo("objectId", user.get("member")["objectId"])
        ..includeObject(["students", "student"]);
      var stuRep = await query.query();
      print("--------${stuRep.count}");
      if (stuRep.results != null && stuRep.success&&stuRep.results.first["student"]!=null) {
        List<QueryBuilder> list = [];
        var querySign = QueryBuilder(ParseObject("StudentSignIn"))
          ..whereEqualTo("student", stuRep.results.first['student'])
          ..includeObject(['student'])
          ..whereGreaterThan(
              "date",
              DateTime.parse(
                  formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd])));
        var rep = await querySign.query();
        if (rep.results != null && rep.success) {
          setState(() {
            listStu = rep.results
                .map(
                  (e) => {
                "state": e["state"],
                "name": e["student"]["displayName"],
                "color": 0Xff72c0a4,
                "stuId": e["student"]["objectId"],
                "signId": e["objectId"]
              },
            )
                .toList();
          });
        } else {
          setState(() {
            listStu = stuRep.results.map(
                  (e) {
                listStu=[];
                if (e.containsKey("student") != false) {
                  return {
                    "state": "init",
                    "name": e["student"]["displayName"],
                    "color": 0Xff72c0a4,
                    "stuId": e["student"]["objectId"],
                    "signId": "NULL"
                  };
                }
              },
            ).toList();
          });
        }
        Provide.value<Counter>(context).increment(listStu);
      } else {
        print("沒有學生");
      }
    }
  }

  //補習
  Future<void> _getTuitionService() async {
    _dyServiceList.clear();
    QueryBuilder<ParseObject> queryComment =
    QueryBuilder<ParseObject>(ParseObject('TuitionService'))
      ..includeObject(['category']);
//    只查6條紀錄
    queryComment.setLimit(6);
    var apiResponse = await queryComment.query();

    if (apiResponse.success && apiResponse.results != null) {
      setState(() {
        _loadingTui = false;
        apiResponse.results.map((f) {
          _dyServiceList.add({
            'objectId': f['objectId'],
            'title': f['title'],
            'src': f['category']['cover'] != null
                ? f['category']['cover']['url']
                : null,
            'category': f['category']['title'],
            'blView': false,
            'titleColor': Colors.amberAccent
          });
        }).toList(growable: false);
        _dyServiceList[0]['blView'] = false;
      });
    } else {
      setState(() => _loadingTui = false);
    }
  }

  //廣告新聞
  Future<void> _getAdvertisement() async {
    print('下拉刷新列表');
//    _describeList.clear();
    var response = await ParseObject('Article').getAll();
    if (response.success && response.results != null) {
    } else {
      setState(() => isNews = false);
    }
  }

  Future<void> _initUser() async {
    final ParseUser parseUser = await ParseUser.currentUser() as ParseUser;
    setState(() {
      user = parseUser;
    });
  }

  Offset pointerStart;
  Offset pointerEnd;

//----------  顶部导航控制

  var hidden = false;
  var offstage = false;

// -------------------
  var ll = Listener(
    onPointerDown: (event) {
      //保存触摸按下的位置信息
      print(event.position);
    },
  );

  @override
  void initState() {
    super.initState();
    print('初始化方法被掉用');
    _initUser();
    _getCourse();
    _getAdvertisement();
    _getTuitionService();
    getDeviceInfo();
    getMemberStudent();

    _scrollController
      ..addListener(() {
        setState(() {
          if (_scrollController.offset > titleHeight) {
            print(_scrollController.offset);
            _titleAlpha = 255;
          } else if (_scrollController.offset <= 0) {
            _titleAlpha = 0;
          } else {
            _titleAlpha = _scrollController.offset * 255 ~/ titleHeight;
          }
        });
      });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _ieItsController.dispose();
  }

  static const platformChannel = const MethodChannel('com.macauscholar.app');

  ///设备信息
  Map deviceMap = {};

  /// 获取设备信息
  Future getDeviceInfo() async {
    platformChannel.setMethodCallHandler((call) {
      setState(() {
        deviceMap = call.arguments;
        print("===+++${deviceMap['deviceToken']}");
        registeredDevice();
      });
      return null;
    });
  }

  /// 注册设备
  Future<void> registeredDevice() async {
    var device = "android";
    if (Platform.isIOS) {
      device = "ios";
    } else {
      device = "android";
    }
    final install = await ParseInstallation.currentInstallation();

    install.set(
        "pushType", device == "android" ? deviceMap["pushType"] : "apns");
    install.set("deviceType", device);
    install.set("deviceToken", deviceMap["deviceToken"]);

    var rep = await install.save();
    if (rep.success) {
      print("設備註冊成功");
    } else {
      print("設備註冊失敗");
    }
  }

  /// 顶部控件数据
  List<dynamic> listIndexTopData = [
    {
      "title": "出勤紀錄",
      "imagePath": "images/attendance_record.png",
      "path": "/index/subpage/AttendanceRecordPage"
    },
    {
      "title": "膳食",
      "imagePath": "images/diet.png",
      "path": "/index/subpage/diet"
    },
    {
      "title": "成長紀錄",
      "imagePath": "images/growth_record.png",
      "path": "/index/subpage/growUp"
    },
    {
      "title": "訂單紀錄",
      "imagePath": "images/index_order.png",
      "path": "/index/subpage/order"
    },
    {
      "title": "學生信息",
      "imagePath": "images/student_message.png",
      "path": "/index/subpage/information"
    },
    {
      "title": "學生相冊",
      "imagePath": "images/album.png",
      "path": "/index/subpage/studentAlbum"
    },
    {
      "title": "訂閱服務",
      "imagePath": "images/index_service.png",
      "path": "/index/subpage/service"
    },
    {
      "title": "家長列表",
      "imagePath": "images/parents.png",
      "path": "/index/subpage/parents"
    },
  ];


//  頂部导航栏
  Widget _indexTopNavigation() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: List.generate(
              4,
                  (index) => GridViewItem(
                title: listIndexTopData[index]['title'],
                imagePath: listIndexTopData[index]['imagePath'],
                onPressed: () => Application.jump(
                    context,
                    user == null
                        ? '/login'
                        : listIndexTopData[index]['path']),
              )),
        ),
        SizedBox(height: 10),
        Offstage(
          offstage: offstage,
          child: AnimatedOpacity(
            opacity: hidden ? 0 : 1,
            duration: Duration(milliseconds: 200),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: List.generate(
                  4,
                      (index) => GridViewItem(
                    title: listIndexTopData[index + 4]['title'],
                    imagePath: listIndexTopData[index + 4]['imagePath'],
                    onPressed: () => Application.jump(
                        context,
                        user == null
                            ? '/login'
                            : listIndexTopData[index + 4]['path']),
                  )),
            ),
            onEnd: () {
              setState(() {
                offstage = hidden;
              });
            },
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
          children: <Widget>[
            _IndexTop(),
            Expanded(
              child: EasyRefresh(
                  header: PhoenixHeader(),
                  footer: PhoenixFooter(),
                  onRefresh: () async {
                    // _getTuitionService();
                    // _getCourse();
                    getMemberStudent();
                  },
                  child: Container(
                      child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            //廣告
                            _newWidget(),

                            /// 課程
                            _courseWidget(),

                            ///補習
                            _tuitionService(),
                          ]))),
            )
          ],
        ));
  }

  /// 内容区域骨架屏
  Widget _contentShimmer() {
    return Column(
      children: [
        Shimmer.fromColors(
            child: CoinRankingListItemSkeleton(
              isTitle: true,
              cardHeight: 205,
              cardWidth: 160,
            ),
            baseColor: Colors.grey,
            highlightColor: Colors.white),
        Row(
          children: [
            SizedBox(
              height: ScreenUtil().setHeight(205),
              child: Shimmer.fromColors(
                  child: CoinRankingListItemSkeleton(
                    isTitle: false,
                    cardHeight: 205,
                    cardWidth: 160,
                  ),
                  baseColor: Colors.grey,
                  highlightColor: Colors.white),
            ),
            SizedBox(
              height: ScreenUtil().setHeight(205),
              child: Shimmer.fromColors(
                  child: CoinRankingListItemSkeleton(
                    isTitle: false,
                    cardHeight: 205,
                    cardWidth: 160,
                  ),
                  baseColor: Colors.grey,
                  highlightColor: Colors.white),
            ),
          ],
        )
      ],
    );
  }

  /// 頭部導航欄
  Widget _IndexTop() {
    return AnimatedSize(
      duration: Duration(milliseconds: 200),
      vsync: this,
      child: Container(
        margin: EdgeInsets.only(bottom: 5),
        padding: EdgeInsets.only(bottom: 8, top: 8),
        decoration: BoxDecoration(
            color: Color(0Xff4d80c5),
            borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(25),
                bottomRight: Radius.circular(25))),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            //導航欄
            Container(
              margin: EdgeInsets.only(left: 15, right: 15),
              width: MediaQuery.of(context).size.width,
              // height: ScreenUtil().setHeight(136),
              child: _indexTopNavigation(),
            ),
            GestureDetector(
              onVerticalDragUpdate: (details) {
                if (details.localPosition.direction > 0) {
                  setState(() {
                    hidden = false;
                  });
                } else if (details.localPosition.direction < 0) {
                  setState(() {
                    hidden = true;
                  });
                }
              },
              child: Container(
                margin: EdgeInsets.only(top: ScreenUtil().setSp(8)),
                width: ScreenUtil().setWidth(160),
                height: 5,
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                        color: Colors.white,
                        width: 3,
                        style: BorderStyle.solid),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 廣告通告組件
  Widget _newWidget() {
    //images/Rectangle.png
    return Container(
      width: ScreenUtil().setWidth(340),
      height: ScreenUtil().setHeight(165),
      decoration:
      BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20))),
      child: Image.asset(
        "images/Rectangle.png",
        fit: BoxFit.fill,
      ),
    );
  }

  //// 課程
  Widget _courseWidget() {
    if (_loadingCou == true) {
      return _contentShimmer();
    } else if (listCourse.length == 0) {
      /// 如果補習數據為空，則不顯示
      return Container();
    } else {
      return CourseTutorial(
        listTuitionService: listCourse,
        path: '/curriculum/details',
        mainTitle: '課程',
        subtitle: '',
        isId: true,
        mainColor: Color(0xff269564),
        subColor: Color(0xff69BF97),
      );
    }
  }

  //// 補習區域
  Widget _tuitionService() {
    if (_loadingTui == true) {
      return _contentShimmer();
    } else if (_dyServiceList.length == 0) {
      /// 如果補習數據為空，則不顯示
      return Container();
    } else {
      return CourseTutorial(
        listTuitionService: _dyServiceList,
        path: '/signTutoria',
        mainTitle: '補習',
//        subtitle: '現正擴大招生',
        isId: true,
        mainColor: Color(0xff269564),
        subColor: Color(0xff69BF97),
      );
    }
  }
}
